package spatialmarketplace.cem.action;

import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidationError;
import spatialmarketplace.cem.dao.SMAdDao;
import spatialmarketplace.cem.dao.implementation.SMAdDaoImpl;
import spatialmarketplace.cem.model.Group;
import spatialmarketplace.cem.model.SMAd;
import spatialmarketplace.cem.model.User;

/**
 * Class that manage all the welcome screen business logic
 * @author Laura Andreina
 */
public class WelcomeScreenActionBean extends GroupActionBean {

    private static final Log logger = Log.getInstance(WelcomeScreenActionBean.class);
    private static final String VIEW = "/WEB-INF/jsp/welcome.jsp";
    List<Group> groupsResults = new ArrayList<Group>();
    private User user;
    List<Group> myGroups = new ArrayList<Group>();
    private ArrayList<SMAd> adList;

    public List<Group> getGroupsResults() {
        return groupsResults;
    }

    public void setGroupsResults(List<Group> groupsResults) {
        this.groupsResults = groupsResults;
    }

    @DefaultHandler
    public Resolution view() {
        /*
         * User Id 2 is hardcoded to show Torab's information. This method saves
         * the current user in the session using the context. If we had a login
         * function, we would call this method after a successful login.
         */
        loadAdList ();
        groupsResults = getAllGroups();

        return new ForwardResolution(VIEW);
    }

    /**
     * To join in a group
     * @return 
     */
    public Resolution join() {
        Integer userId = getContext().getUserId();
        Integer groupId = getGroupId();
        String notificationDetails = getContext().getUserName() + " has joined " + getContext().getRequest().getParameter("name");

        try {

            getGroupDao().joinGroup(groupId, userId);
            getContext().getMessages().add(new SimpleMessage("Your request to join a group has been sent."));
            getNotificationDao().createNotification(groupId, 1, notificationDetails);

        } catch (Exception e) {
            ValidationError error = new SimpleError("The request cannot be sent.");
            getContext().getValidationErrors().add("groupId", error);
            logger.error("Error" + e);
            System.out.println("Error: " + WelcomeScreenActionBean.class.getName() + ", " + e);
        }
        loadAdList ();
        groupsResults = getAllGroups();
        return new ForwardResolution(VIEW);
    }

    public void setUsers(User user) {
        this.user = user;
    }

    /**
     * Method to search existing groups according to the field entered
     * @return search jsp
     */
    public Resolution search() {
        String keywords = "";
        Group group = getGroup();
        keywords = group.getName();
        Integer userId = getContext().getUserId();
        if (keywords == null || keywords.equals("")) {
            groupsResults = getAllGroups();
        } else {
            try {
                groupsResults = getGroupDao().search(keywords, userId);

            } catch (Exception e) {
                ValidationError error = new SimpleError(keywords + " Groups seacrhed cannot be displayed.");
                getContext().getValidationErrors().add("keywords", error);
                logger.error("Error" + e);
                System.out.println("Error: " + WelcomeScreenActionBean.class.getName() + ", " + e);
            }
        }
        loadAdList ();
        return new ForwardResolution(VIEW);
    }

    /**
     * Method to get all the existing groups for search view
     * @return all the existing groups
     */
    public List<Group> getAllGroups() {
        Integer userId = getContext().getUserId();

        try {
            groupsResults = getGroupDao().read(userId);

        } catch (Exception e) {
            ValidationError error = new SimpleError(groupsResults + " Groups cannot be displayed.");
            getContext().getValidationErrors().add("groupsResults", error);
            logger.error("Error" + e);
            System.out.println("Error: " + WelcomeScreenActionBean.class.getName() + ", " + e);
        }
        return groupsResults;
    }

    /**
     * Get all my groups
     * @return all groups I belong to.
     */
    public List<Group> getMyGroups() {


        Integer userId = getContext().getUserId();
        try {
            myGroups = getGroupDao().getMyGroups(userId);
            System.out.println("SIZE ------ "+myGroups.size());

        } catch (Exception e) {
            ValidationError error = new SimpleError(myGroups + " The list of group cannot be displayed.");
            getContext().getValidationErrors().add("myGroups", error);
            logger.error("Error" + e);
            System.out.println("Error: " + WelcomeScreenActionBean.class.getName() + ", " + e);
        }

        return myGroups;
    }
    
    /**
     * Loads the list of ads from the database.
     */
    public void loadAdList (){
        SMAdDao smAdDao = SMAdDaoImpl.getInstance();
        adList = smAdDao.readAllAds();
    }

    public ArrayList<SMAd> getAdList() {
        return adList;
    }

}
